<template>
  <div>
    <el-upload
      v-loading="loadingFlag"
      :action="fileUrl"
      class="file-uploader"
      :on-preview="handlePreview"
      :show-file-list="true"
      multiple
      :limit="5"
      :on-exceed="handleExceed"
      :on-success="onSuccess"
      :file-list="fileList"
    >
      <el-button v-if="dialogType=== 'add'" size="small" type="primary">点击上传</el-button>
      <div v-if="dialogType==='add'" slot="tip" class="el-upload__tip">上传文件不超过20MB</div>
    </el-upload>
    <el-image-viewer
      v-if="imagePreview"
      :on-close="closeViewer"
      :url-list="[url]"
    />
  </div>
</template>

<script>
import { fileUrl, staticImgUrl } from '@/url'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'UploadFile',
  components: {
    ElImageViewer
  },
  props: {
    files: {
      type: String,
      default: ''
    },
    dialogType: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      //  文件列表
      fileList: [],
      resultList: [],
      fileUrl: fileUrl,
      loadingFlag: false,
      imagePreview: false,
      url: ''
    }
  },
  watch: {
    files(val) {
      if (val !== null) {
        if (this.files) {
          this.initFile()
        }
      }
    }
  },
  created() {
    if (this.files) {
      this.initFile()
    }
  },
  methods: {
    initFile() {
      // [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      if (this.files) {
        this.fileList = JSON.parse(this.files)
        this.resultList = JSON.parse(this.files)
      }
    },
    handlePreview(file) {
      console.log(file.url)
      this.url = staticImgUrl + file.url
      this.imagePreview = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeAvatarUpload(file) {
      const isLt6M = file.size / 1024 / 1024 < 20
      if (!isLt6M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
        this.loadingFlag = false
      }
      return isLt6M
    },
    onSuccess(res, file, fileList) {
      console.log(res, file, fileList)
      this.resultList.push({
        name: file.name,
        url: file.response.picture_url
      })
    },
    getFiles() {
      return this.resultList
    },
    closeViewer() {
      this.imagePreview = false
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
